//
//  XPEmojiKeyboardView.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/20.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit

let XPEmojiKeyboardDisplayViewCellId = "XPEmojiKeyboardDisplayViewCellId"


let flowLayout = UICollectionViewFlowLayout()
class XPEmojiKeyboardView: UIView {
    
    // 判断是否是点击Emoji键盘的toolBar让键盘滚动
    var isClickToolBar = false
    
    /// keyboardToolbar
    private lazy var emojiKeyboardToolBar: XPEmojiKeyboardToolBar = XPEmojiKeyboardToolBar(frame: CGRectZero)
    
    /// 显示表情键盘的视图
    private lazy var emojiDisplayView: UICollectionView = {
        let emojiDisplayView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        flowLayout.scrollDirection = .Horizontal
        flowLayout.minimumLineSpacing = 0
        emojiDisplayView.showsHorizontalScrollIndicator = false
        emojiDisplayView.pagingEnabled = true
        emojiDisplayView.bounces = false
        emojiDisplayView.registerClass(XPEmojiDisplayCell.self, forCellWithReuseIdentifier: XPEmojiKeyboardDisplayViewCellId)
        emojiDisplayView.dataSource = self
        emojiDisplayView.delegate  = self
        emojiDisplayView.backgroundColor = randomColor()
        return emojiDisplayView
    }()


    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        // 处理toolBar点击事件的回调
        handleClickEvents()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = randomColor()
        addSubview(emojiKeyboardToolBar)
        addSubview(emojiDisplayView)
        
        emojiKeyboardToolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.height.equalTo(44)
        }
        
        emojiDisplayView.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(emojiKeyboardToolBar.snp_top)
            make.top.equalTo(self)
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
        }
    }
    
    private func handleClickEvents() {
        emojiKeyboardToolBar.selectedButtonClosure = {[weak self] (type: XPToolBarButtonSelectedType) in
            var indexPath: NSIndexPath
            
            self?.isClickToolBar = true
            
            switch type {
                case .Normal:
                    indexPath = NSIndexPath(forItem: 0, inSection: 0)
                case .Emoji:
                    indexPath = NSIndexPath(forItem: 0, inSection: 1)
                case .Lxh:
                    indexPath = NSIndexPath(forItem: 0, inSection: 2)
            }
            self?.emojiDisplayView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: false)
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        flowLayout.itemSize = emojiDisplayView.size
    }
}

// MARK: - collectionView的数据源和代理方法
extension XPEmojiKeyboardView: UICollectionViewDataSource, UICollectionViewDelegate {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return XPEmojiTool.sharedTool.emoticonCollection.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return XPEmojiTool.sharedTool.emoticonCollection[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(XPEmojiKeyboardDisplayViewCellId, forIndexPath: indexPath) as! XPEmojiDisplayCell
        
        cell.emoticons = XPEmojiTool.sharedTool.emoticonCollection[indexPath.section][indexPath.item]
        return cell
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        isClickToolBar = false
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        if isClickToolBar { return }
        
        let currentOffsetX = scrollView.contentOffset.x
        // 获得当前显示的cell
        let cells = emojiDisplayView.visibleCells().sort { (firstCell, secondCell) -> Bool in
            return firstCell.x < secondCell.x
        }
 
        let firstCell = cells.first!
        let secondCell = cells.last!
        
        let firstCellContentOffsetX = abs(firstCell.x - currentOffsetX)
        let secondCellContentOffsetX = abs(secondCell.x - currentOffsetX)
        
        var indexPath: NSIndexPath = NSIndexPath(forItem: 0, inSection: 0)
        if firstCellContentOffsetX < secondCellContentOffsetX {
            indexPath = emojiDisplayView.indexPathForCell(firstCell)!
        }else {
            indexPath = emojiDisplayView.indexPathForCell(secondCell)!
        }
        
        emojiKeyboardToolBar.autoSelectButton(indexPath.section)
    }
}
